import 'dart:convert';

import 'package:hambuk/screen/video_player.dart';
import 'package:hambuk/util/ToastUtil.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';

import '../model/MoreFilmModel.dart';
import '../service/HttpService.dart';
import '../widget/scaffold_layout_builder.dart';

class MoreVedio extends StatefulWidget {
  /*参数*/
  final int id;

  const MoreVedio({super.key, required this.id});

  @override
  State<MoreVedio> createState() => _MoreVedioState();
}

class _MoreVedioState extends State<MoreVedio> {
  /*依赖引入*/
  final HttpService httpService = HttpService();

  /*常量定义*/
  late bool isLoading = false;
  late String name = "";
  late String cover = "";
  late List<EpisodeModel> episodesList = [];

/*获取详细数据*/
  Future<void> init() async {
    final detailed = await httpService.getVideoDetail(widget.id);
    if (detailed != null) {
      final responseData = json.decode(detailed.body)['data'];
      final List episodes = responseData['episodes'];
      if (episodes.isEmpty) {
        ToastUtil().ToastUtils("无法播放请重试");
      } else {
        List r = episodes.map((e) => EpisodeModel.fromJson(e)).toList();
        setState(() {
          episodesList.addAll(r as Iterable<EpisodeModel>);
        });
      }
      setState(() {
        name = responseData['name'];
        cover = responseData['cover'];
        /*可显示*/
        isLoading = true;
      });
    }
  }

  @override
  void initState() {
    init();
    super.initState();
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    if (isLoading) {
      return Scaffold(
        body: ScaffoldLayoutBuilder(
          backgroundColorAppBar:
              const ColorBuilder(Colors.transparent, Color(0xFFED1F69)),
          textColorAppBar: const ColorBuilder(Colors.white),
          appBarBuilder: _appBar,
          child: SingleChildScrollView(
            child: Stack(
              children: [
                CachedNetworkImage(
                  imageUrl: cover,
                  width: MediaQuery.of(context).size.width,
                  height: MediaQuery.of(context).size.height * 0.7,
                  fit: BoxFit.cover,
                  errorWidget: (context, url, error) => Image.asset(
                    'assets/image/ic_load.png',
                    fit: BoxFit.cover,
                  ),
                ),
                Container(
                  margin: EdgeInsets.only(
                    top: MediaQuery.of(context).size.height * 0.6,
                  ),
                  decoration: const BoxDecoration(
                    borderRadius: BorderRadius.vertical(
                      top: Radius.circular(40),
                    ),
                    color: Colors.white,
                  ),
                  child: NotificationListener<ScrollNotification>(
                    child: RepaintBoundary(
                      child: Column(
                        children: [
                          Container(
                            alignment: Alignment.center,
                            padding: const EdgeInsets.only(top: 15),
                            child: const Text("--- قىسىم تاللاش ---",
                                style: TextStyle(
                                    color: Colors.black,
                                    fontWeight: FontWeight.w400,
                                    fontSize: 16)),
                          ),
                          Container(
                            margin: const EdgeInsets.only(
                                bottom: 25, left: 8, right: 8, top: 10),
                            child: GridView.builder(
                              gridDelegate:
                                  const SliverGridDelegateWithFixedCrossAxisCount(
                                crossAxisCount: 4,
                                childAspectRatio: 2,
                                crossAxisSpacing: 8.0, // 设置水平方向元素之间的间距
                                mainAxisSpacing: 8.0, // 设置垂直方向元素之间的间距
                              ),
                              //* 移除上方的空格 *//
                              padding: const EdgeInsets.all(1),
                              shrinkWrap: true,
                              addAutomaticKeepAlives: false,
                              addRepaintBoundaries: false,
                              physics: const BouncingScrollPhysics(),
                              itemCount: episodesList.length,
                              itemBuilder: (BuildContext context, int index) {
                                return SizedBox(
                                  child: Column(
                                    children: [
                                      Expanded(
                                        child: GestureDetector(
                                          onTap: () async {
                                            /*String? url = await httpService.getVideoUrl(widget.id); 获取单个电影数据*/
                                            String? url = await httpService
                                                .getVideoUrlMore(
                                                    episodesList[index]
                                                        .id); /*获取多集电影播放地址*/
                                            if (url != null) {
                                              Navigator.push(
                                                context,
                                                MaterialPageRoute(
                                                  builder: (context) =>
                                                      VideoPlayerM(
                                                          url: url,
                                                          icon: '',
                                                          title: ''),
                                                ),
                                              );
                                            }
                                          },
                                          child: Container(
                                            decoration: BoxDecoration(
                                              border: Border.all(
                                                  color: Colors.black,
                                                  width: 1),
                                              borderRadius:
                                                  const BorderRadius.all(
                                                      Radius.circular(15)),
                                              color: const Color(0xFFED1F69),
                                            ),
                                            child: Center(
                                              child: Text(
                                                "第 ${episodesList[index].episode_num} 集",
                                                style: const TextStyle(
                                                  color: Colors.white,
                                                  fontWeight: FontWeight.bold,
                                                  fontSize: 12,
                                                ),
                                              ),
                                            ),
                                          ),
                                        ),
                                      ),
                                    ],
                                  ),
                                );
                              },
                            ),
                          ),
                        ],
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),
        ),
      );
    } else {
      return Scaffold(
        body: Column(
          children: [
            Flexible(
              child: Stack(
                children: [
                  Center(
                      child: Text(
                    "Loading...",
                    style: TextStyle(
                      color: ColorTween(
                        begin: const Color(0xFFED1D24),
                        end: const Color(0xFFED1F69),
                      ).lerp(0.5),
                      fontSize: 24,
                      fontWeight: FontWeight.bold,
                    ),
                  ))
                ],
              ),
            ),
          ],
        ),
      );
    }
  }

  Widget _appBar(BuildContext context, ColorAnimated colorAnimated) {
    return AppBar(
      backgroundColor: colorAnimated.background,
      elevation: 0,
      title: Text(
        name,
        style: TextStyle(
            color: colorAnimated.color,
            fontWeight: FontWeight.bold,
            fontSize: 16),
      ),
      leading: GestureDetector(
        onTap: () => {Navigator.pop(context)},
        child: Icon(
          Icons.arrow_back_ios_new_rounded,
          color: colorAnimated.color,
        ),
      ),
      /*actions: [
        IconButton(
          onPressed: () {},
          icon: Icon(
            Icons.favorite,
            color: colorAnimated.color,
          ),
        ),
      ],*/
    );
  }
}
